<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <!-- <script src="./node_modules/bluebird/js/browser/bluebird.min.js"></script> -->
  <style> 
    .ball{
      width: 40px;
      height: 40px;
      border-radius: 20px;
    }
    .ball1 {
      background: red;
    }
    .ball2 {
      background: yellow;
    }
    .ball3 {
      background: green;
    }
  </style>
</head>
<body>
  <div class="ball ball1" style="margin-left: 0"></div>
  <div class="ball ball2" style="margin-left: 0"></div>
  <div class="ball ball3" style="margin-left: 0"></div>

  <script>
    var ball1 = document.querySelector('.ball1')
    var ball2 = document.querySelector('.ball2')
    var ball3 = document.querySelector('.ball3')

    function animate(ball, distance, cb) {
      setTimeout(function() {
        var marginLeft = parseInt(ball.style.marginLeft)

        if (marginLeft === distance) {
          cb && cb()
        } else {
          if (marginLeft < distance) {
            marginLeft = marginLeft + 1
          } else {
            marginLeft = marginLeft - 1
          }
          ball.style.marginLeft = `${marginLeft}px`
          animate(ball, distance, cb)
        }
      }, 13); // 1秒钟60帧是比较流畅的帧率，平均是16。jQuery中默认是13毫秒。
    }


    // animate(ball1, 100, function() {
    //   animate(ball2, 200, function() {
    //     animate(ball3, 300, function() {
    //       animate(ball3, 150, function() {
    //         animate(ball2, 150, function() {
    //           animate(ball1, 150, function() {
    //               console.log('ik')
    //           })
    //         })
    //       })
    //     })
    //   })
    // })

    // var Promise = window.Promise
    function promiseAnimate(ball, distance) {
      return new Promise(function(resolve, reject) {
        animate(ball, distance, resolve)
      }) 
    }

    promiseAnimate(ball1, 100).then(() => {
      return promiseAnimate(ball2, 200)
    }).then(() => {
      return promiseAnimate(ball3, 300)
    }).then(() => {
      return promiseAnimate(ball3, 100)
    }).then(() => {
      return promiseAnimate(ball2, 100)
    }).then(() => {
      return promiseAnimate(ball1, 100)
    })



     
  </script>
</body>
</html>